import React, { useState } from 'react';
import { Form, Input, Button, Alert, Typography, Space } from 'antd';
import { useFormChainEffectEngine, FormChainEffectMap } from 'form-chain-effect-engine';

const { Title, Paragraph } = Typography;

const FormChainEffectEngineDemo: React.FC = () => {
  const [form] = Form.useForm();
  const [bWarning, setBWarning] = useState(false);
  const [cWarning, setCWarning] = useState(false);
  const [stopMsg, setStopMsg] = useState('');

  // 配置
  const injectedConfig = {
    a: {
      dependents: ['b'],
      effect: (value: any, allValues: any, chain) => {
        setStopMsg('');
        console.log('Effect: a triggered, chain path:', chain.path.join(' → '));
        if (value === 'stop') {
          chain.stop?.();
          setStopMsg('链路在 A 被停止了');
          return;
        }
        // 正常流程，修改 b
        setBWarning(false);
        form.setFieldsValue({ b: `由 A 自动填充，输入是: ${value}` });
      }
    },
    b: {
      dependents: ['c'],
      effect: (value: any, allValues: any, chain) => {
        console.log('Effect: b triggered, chain path:', chain.path.join(' → '));
        const aVal = allValues.a;
        setBWarning(true);
        if (aVal && aVal.length < 3) {
          form.setFieldsValue({ b: '自动填充b' });
          setBWarning(true);
        } else {
          setBWarning(false);
        }
      }
    },
    c: {
      dependents: [],
      effect: (value: any, allValues: any, chain) => {
        console.log('Effect: c triggered, chain path:', chain.path.join(' → '));
        const bVal = allValues.b;
        if (!!bVal && bVal.includes('填充')) {
          setCWarning(true);
          form.setFieldsValue({ c: '自动填充c' });
        }
      }
    }
  } as FormChainEffectMap;

  const { onValuesChange, manualTrigger } = useFormChainEffectEngine({
    form,
    config: injectedConfig,
    options: {
      enableAdvancedControl: true
    }
  });

  return (
    <div style={{ maxWidth: 600, margin: '20px auto' }}>
      <Title level={3}>表单依赖链示例</Title>
      <Paragraph>
        <ul>
          <li>输入A时，正常执行链路，自动填充 B 和 C。</li>
          <li>输入B时，正常执行链路，自动填充 C。</li>
          <li>
            输入 <code>stop</code> 在 A，会停止链路执行，不触发 B和C。
          </li>
          <li>控制台打印链路路径，便于调试。</li>
        </ul>
      </Paragraph>
      <Form
        form={form}
        layout="vertical"
        onValuesChange={onValuesChange}
        onFinish={(v) => console.log('提交的表单值:', v)}
      >
        <Form.Item name="a" label="字段 A">
          <Input placeholder="输入 stop 或其他任意值" />
        </Form.Item>
        <Button
          onClick={() => {
            form.setFieldValue('a', '1');
            manualTrigger('a', '1');
          }}
        >
          测试写入 1
        </Button>
        <Button
          onClick={() => {
            form.setFieldValue('a', '111');
            manualTrigger('a', '111');
          }}
        >
          测试写入 111
        </Button>
        <Button
          onClick={() => {
            form.setFieldValue('a', 'stop');
            manualTrigger('a', 'stop');
          }}
        >
          测试写入 stop
        </Button>
        <Form.Item name="b" label="字段 B">
          <Input placeholder="由 A 触发变化" />
        </Form.Item>
        <div>{bWarning && <Alert type="warning" message="B 被 A 自动填充了" />}</div>
        <Button
          onClick={() => {
            form.setFieldValue('b', 'bbb');
            manualTrigger('b', 'bbb');
          }}
        >
          测试写入 bbb
        </Button>
        <Button
          onClick={() => {
            form.setFieldValue('b', '填充bbb');
            manualTrigger('b', '填充bbb');
          }}
        >
          测试写入 填充bbb
        </Button>

        <Form.Item name="c" label="字段 C">
          <Input placeholder="由 B 触发变化" />
        </Form.Item>
        <div>
          {cWarning && <Alert type="info" message="C 检测到 B 包含关键字‘填充’自动填充C" />}
        </div>

        <Space direction="vertical" style={{ marginBottom: 16 }}>
          {stopMsg && <Alert type="error" message={stopMsg} />}
        </Space>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default FormChainEffectEngineDemo;
